package com.liauto.timelist.ui.list

import android.content.Context
import android.os.SystemClock
import android.util.Log
import androidx.lifecycle.ViewModel
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.liauto.timelist.BuildConfig
import com.liauto.timelist.util.HttpUtil
import com.liauto.timelist.util.ShareUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.concurrent.thread

class ListViewModel : ViewModel() {
    companion object {
        private const val TIME_LIST_BEAN = "TIME_LIST_BEAN"
    }

    suspend fun getTimeList(context: Context): TimeListBean = withContext(Dispatchers.IO) {
        ShareUtil.getString(TIME_LIST_BEAN, context)?.let { s ->
            thread {
                HttpUtil.getRequest(
                    BuildConfig.TIME_LIST
                ) {
                    Log.i("TAG", "getTimeList: $it")
                    if (it.success) {
                        ShareUtil.putString(TIME_LIST_BEAN, it.content, context)
                    }
                }
            }
            return@withContext Gson().fromJson(s, TimeListBean::class.java)
        }
        var listBean = TimeListBean()
        HttpUtil.getRequest(
            BuildConfig.TIME_LIST
        ) {
            Log.i("TAG", "getTimeList: $it")
            if (it.success) {
                listBean = Gson().fromJson(it.content, TimeListBean::class.java)
                Log.i("TAG", "getTimeList: $listBean")
            }
        }
        return@withContext listBean
    }


    suspend fun getTimeList2(context: Context): TimeListBean = withContext(Dispatchers.IO) {
        var listBean = TimeListBean()
        //判断缓存
        ShareUtil.getString(TIME_LIST_BEAN, context)?.let {
            return@withContext Gson().fromJson(it, TimeListBean::class.java)
        }
        HttpUtil.getRequest(
            BuildConfig.TIME_LIST
        ) {
            Log.i("TAG", "getTimeList: $it")
            if (it.success) {
                listBean = Gson().fromJson(it.content, TimeListBean::class.java)
                Log.i("TAG", "getTimeList: $listBean")
            }
        }
        return@withContext listBean
    }
}

data class TimeListBean(
    @SerializedName("code") val code: Int = 0,
    @SerializedName("message") val message: String? = null,
    @SerializedName("data") var data: MutableList<Data> = mutableListOf()
) {
    data class Data(
        @SerializedName("name") val name: String? = null,
        @SerializedName("hour") val hour: Int = 0,
        @SerializedName("min") val min: Int = 0
    )
}